<?php

namespace MSDK\Model;

/**
 * 角色数据库模型
 *
 * @author SoChishun <14507247@qq.com>
 * @version 1.0
 * @since 1.0.0 <2015-3-25> SoChishun Added.
 */
class MSDKRoleModel extends AppbaseModel {

    /**
     * 数据表名称
     * @var string
     */
    protected $tableName = 'tuser_role';

    /**
     * 命名范围
     * @var array
     */
    protected $_scope = array(
        'treeselect' => array(
            'field' => 'id, role_name as text'
        ),
        'treetable' => array(
            'field' => array('id', 'role_name', 'parent_id', 'role_code', 'ordinal', 'remark', 'state', 'create_time'),
            'order' => 'ordinal,id'
        ),
    );

    /**
     * 是否批量验证
     * @var boolean
     */
    protected $patchValidate = true;

    /**
     * 返回树形列表或刷新缓存
     * 
     * @param string $scope 命名范围
     * @since 1.0 <2015-3-25> SoChishun Added.
     */
    public function get_tree_list($scope = '', $where = '') {
        $out = array();
        for ($i = 1; $i < 10; $i++) {
            $out[] = array('id' => $i, 'role_name' => '管理员 ' . $i, 'parent_id' => 0, 'role_code' => 'XXX' . $i, 'orginal' => $i, 'state' => 1, 'create_time' => '2015-09-11 18:08:30');
        }
        return $out;
    }

    /**
     * 保存角色
     * @return true|string|array
     * @since 1.0 2015-3-6 by sutroon
     */
    public function save_role() {
        $rules = array(
            array('role_name', 'require', '角色必须填写!'),
            array('state', 'number', '状态有误!'),
        );
        if (!$this->validate($rules)->create()) {
            $this->returnMsg(false, $this->getError());
        }
        if ($this->data['id']) {
            $result = $this->save();
        } else {
            $result = $this->add();
        }
        return $this->returnMsg($result);
    }

    public function delete_role($id = '') {
        if (!$id) {
            return $this->returnMsg(false, '参数无效');
        }
        // 判断是否有子项目
        $list = M()->query('select a.role_name as name from tuser_role a inner join tuser_role b on b.parent_id=a.id where b.parent_id in (' . $id . ')');
        $names = false;
        if ($list) {
            foreach ($list as $row) {
                $names.=',' . $row['name'];
            }
        }
        if ($names) {
            return $this->returnMsg(false, '以下项目有子项目,请先转移子项目:' . "\n" . ltrim($names, ','));
        }
        // 判断是否有引用
        $user_role_ids = M('tuser_member')->where(array('role_id' => array('in', $id)))->getField('role_id', true);
        if ($user_role_ids) {
            $names = M('tuser_role')->where(array('id' => array('in', $user_role_ids)))->getField('role_name', true);
            return $this->returnMsg(false, '以下项目正在被用户使用,无法删除:' . "\n" . implode(',', $names));
        }
        $result = M('tuser_role')->delete($id);
        return $this->returnMsg($result);
    }

}
